<template>
  <div class="works">
    <div class="header-container">
      <el-page-header title="返回" content="文学作品列表" @back="goBack" />
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入作品标题或作者名称"
          class="search-input"
          @keyup.enter="handleSearch(1)"
          clearable
        />
      </div>
    </div>
    
    <!-- 分类导航 -->
    <div class="categories-navigation">
      <div class="category-container">
        <div 
          v-for="category in categoriesWithSubcategories" 
          :key="category.id" 
          class="category-group"
        >
          <!-- 一级分类名称 -->
          <div class="category-main">
            <span class="category-name">{{ category.name }}</span>
          </div>
          
          <!-- 子分类列表 -->
          <div class="category-content">
          <div class="subcategories" v-if="category.subcategories && category.subcategories.length > 0">
            <div 
              v-for="(subcategory, index) in category.subcategories" 
              :key="subcategory.id"
              class="subcategory-item"
              :class="{ 
                active: selectedCategory === subcategory.id
              }"
              @click="selectCategory(subcategory.id)"
              v-show="index < 10 || isCategoryExpanded(category.id)"
            >
              {{ subcategory.name }}
            </div>
          </div>
          
          <!-- 展开/折叠图标 -->
          <div 
            v-if="expandToggleVisible(category.subcategories)" 
            class="expand-toggle"
            @click="toggleCategory(category.id)"
          >
            <el-icon v-if="!isCategoryExpanded(category.id)"><ArrowDown /></el-icon>
            <el-icon v-else><ArrowUp /></el-icon>
          </div>
        </div>
        </div>
      </div>
    </div>
    
    <!-- 作品列表 -->
    <div class="works-content">
      <el-skeleton :loading="loading" animated>
        <template #template>
          <div class="works-grid">
            <el-card v-for="n in 6" :key="n" class="work-card">
              <el-skeleton-item variant="h3" style="width: 70%" />
              <div>
                <el-skeleton-item variant="text" style="width: 40%" />
                <el-skeleton-item variant="text" style="width: 60%" />
                <el-skeleton-item variant="text" style="width: 50%" />
              </div>
            </el-card>
          </div>
        </template>
         <template #default>
          <div v-if="works.length > 0" class="works-grid">
            <el-card 
              v-for="work in works" 
              :key="work.id" 
              class="work-card"
              @click="goToWorkDetail(work.id)"
              shadow="hover"
            >
              <h3>{{ work.title }}</h3>
              <p class="author">作者: {{ work.author?.name || `作者${work.author_id}` }}    {{ work.author.dynasty }}</p>  <!-- 修改显示逻辑 -->
              <p class="genre" v-if="work.genre">类型: {{ work.genre }}</p>
              <p class="date">创作时间: 公元{{ work.creation_year }}</p>
            </el-card>
          </div>
          <el-empty v-else description="暂无作品" />
        </template>
      </el-skeleton>
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="totalWorks > pageSize">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalWorks"
          layout="prev, pager, next"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { listWorks, getWorksByCategory, searchWorks, getWorksByParentCategory } from '@/api/works'
import { listCategories, getSubcategories } from '@/api/categories'
import type { LiteraryWork } from '@/types'

const router = useRouter()
const route = useRoute()
const works = ref<LiteraryWork[]>([])
const categoriesWithSubcategories = ref<any[]>([])
const selectedCategory = ref<number | null>(null)
const loading = ref(true)
const searchKeyword = ref('')
const isSearching = ref(false)

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(9)
const totalWorks = ref(0)

onMounted(async () => {
  try {
    // 获取所有一级分类及其子分类
    await loadCategoriesWithSubcategories()
    
    // 检查是否有分类参数
    const categoryId = route.query.categoryParent ? Number(route.query.categoryParent) : null;  // 修改这行
    if (categoryId) {
      // 加载指定分类下的作品
      await selectCategoryParent(categoryId);
    } else {
      // 默认加载所有作品
      await loadAllWorks();
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
})

// 加载分类及其子分类
const loadCategoriesWithSubcategories = async () => {
  try {
    // 获取一级分类
    const categories = await listCategories()
    
    // 获取每个一级分类的子分类
    const categoriesWithSub = []
    for (const category of categories) {
      const subcategories = await getSubcategories(category.id)
      categoriesWithSub.push({
        ...category,
        subcategories: subcategories || []
      })
    }
    
    categoriesWithSubcategories.value = categoriesWithSub
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

// 处理作品数据，将author_id转换为author字段
const processWorksData = (response: any): LiteraryWork[] => {
  // 确保response是一个有效的对象，并且包含data属性
  if (!response || !response.data) {
    return [];
  }
  
  // 检查response.data是否包含分页信息
  const worksData = response.data.data ? response.data : { data: response.data, total: 0 };
  
  if (!Array.isArray(worksData.data)) {
    return [];
  }
  
  return worksData.data.map(work => ({
    ...work,
    author: work.author || { name: `作者${work.author_id}` } // 如果没有author字段，使用author_id作为默认值
  }));
}

const loadAllWorks = async (page = 1) => {
  try {
    const response = await listWorks(page, pageSize.value)
    const processedWorks = processWorksData(response)
    works.value = processedWorks
    totalWorks.value = response.data.total || 0
    currentPage.value = page
  } catch (error) {
    console.error('获取作品列表失败:', error)
  }
}

const selectCategoryParent = async (categoryId: number, page = 1) => {
  try {
    loading.value = true
    selectedCategory.value = categoryId
    
    const response = await getWorksByParentCategory(categoryId, page, pageSize.value)
    const processedWorks = processWorksData(response)
    works.value = processedWorks
    totalWorks.value = response.data.total || 0
    currentPage.value = page
  } catch (error) {
    console.error('获取作品失败:', error)
    ElMessage.error('获取作品失败')
  } finally {
    loading.value = false
  }
}

const selectCategory = async (categoryId: number, page = 1) => {
  try {
    loading.value = true
    selectedCategory.value = categoryId
    
    const response = await getWorksByCategory(categoryId, page, pageSize.value)
    const processedWorks = processWorksData(response)
    works.value = processedWorks
    totalWorks.value = response.data.total || 0
    currentPage.value = page
  } catch (error) {
    console.error('获取作品失败:', error)
    ElMessage.error('获取作品失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = async (page = 1) => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，重新加载所有作品
    await loadAllWorks(page)
    return
  }
  
  try {
    loading.value = true
    isSearching.value = true
    
    const response = await searchWorks(searchKeyword.value, page, pageSize.value)
    const processedWorks = processWorksData(response)
    works.value = processedWorks
    totalWorks.value = response.data.total || 0
    currentPage.value = page
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  if (isSearching.value) {
    handleSearch(page)
  } else if (selectedCategory.value) {
    selectCategory(selectedCategory.value, page)
  } else {
    loadAllWorks(page)
  }
}

// 添加用于控制子分类展开/折叠的响应式变量
const expandedCategories = ref<Set<number>>(new Set())

// 切换分类的展开/折叠状态
const toggleCategory = (categoryId: number) => {
  if (expandedCategories.value.has(categoryId)) {
    expandedCategories.value.delete(categoryId)
  } else {
    expandedCategories.value.add(categoryId)
  }
}

// 检查分类是否展开
const isCategoryExpanded = (categoryId: number) => {
  return expandedCategories.value.has(categoryId)
}

const expandToggleVisible = (subcategories: any[]) => {
  // 这里可以根据容器宽度和子分类宽度动态计算是否需要显示展开/折叠图标
  // 暂时使用固定值，实际项目中需要根据实际情况调整
  return true;
}

const goToWorkDetail = (id: number) => {
  router.push(`/works/${id}`)
}

const goBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.works {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-page-header {
  margin-bottom: 0;
}

/* 搜索框 */
.search-container {
  flex: 1;
  max-width: 400px;
  margin-left: 20px;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 30px;
  box-shadow: 0 0 0 2px var(--border-color) inset;
  height: 40px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: var(--primary-color) !important;
}

.search-input :deep(.el-input__inner) {
  font-size: 14px;
  color: var(--text-color-primary);
}

.search-input :deep(.el-input__inner::placeholder) {
  color: var(--text-color-secondary);
}

/* 分类导航 */
.categories-navigation {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid var(--border-color);
}

.category-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.category-group {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 10px 0;
  border-bottom: 1px dashed var(--border-color);
}

.category-group:last-child {
  border-bottom: none;
}

.category-main {
  font-weight: 600;
  color: var(--text-color);
  min-width: 80px;
  font-size: 16px;
  align-self: flex-start;
  margin-top: 6px;
}

.category-content {
  display: flex;
  flex: 1;
  min-width: 0; /* 允许 flex 项目收缩到内容宽度 */
}

.subcategories {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  flex: 1;
  margin-right: 30px; /* 添加右边距，避免覆盖展开图标 */
}

.subcategory-item {
  cursor: pointer;
  font-size: 14px;
  color: var(--text-color);
  transition: all 0.3s;
  padding: 6px 12px;
  border-radius: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border: 1px solid transparent;
}

.subcategory-item:hover {
  color: var(--primary-color);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border-color: var(--primary-color);
  transform: translateY(-2px);
}

.subcategory-item.active {
  color:  var(--text-color); /* 使用主题变量，如果不存在则默认为白色 */
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  font-weight: 500;
}

/* 作品列表 */
.works-content {
  margin-top: 20px;
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.work-card {
  cursor: pointer;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border: 1px solid var(--border-color);
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.work-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.15);
}

.work-card h3 {
  margin-top: 0;
  color: var(--text-color);
  font-size: 1.3em;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 10px;
}

.author, .genre, .date {
  color: var(--text-color);
  margin: 8px 0;
  font-size: 14px;
}

.author {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-container {
    gap: 12px;
  }
  
  .category-group {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
    padding: 15px 0;
  }
  
  .category-main {
    min-width: auto;
  }
  
  .subcategories {
    gap: 10px;
    padding-left: 15px;
  }
  
  .subcategory-item {
    padding: 4px 10px;
    font-size: 13px;
  }

  .pagination-container :deep(.el-pagination) {
    font-size: 12px;
  }
  
  .pagination-container :deep(.el-pagination .el-pagination__jump) {
    margin-left: 5px;
  }
  
  .pagination-container :deep(.el-pagination .el-pagination__editor) {
    width: 40px;
  }
}
/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.subcategory-hidden {
  display: none;
}

.expand-toggle {
  cursor: pointer;
  font-size: 14px;
  color: var(--primary-color);
  display: flex;
  align-items: flex-start;
  margin-top: 6px;
  margin-left: auto;
  flex-shrink: 0; 
}

.expand-toggle span {
  display: flex;
  align-items: center;
}

.expand-toggle i {
  margin-left: 5px;
}

:deep(.el-page-header__content) {
  color: var(--text-color);
  font-weight: 500;
}

:deep(.el-page-header__title) {
  color: var(--text-color);
  opacity: 0.8;
}

/* 确保在暗色主题下也能正确显示 */
[data-theme="dark"] :deep(.el-page-header__content),
[data-theme="dark"] :deep(.el-page-header__title) {
  color: var(--text-color);
}
</style>